﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZK.Common;
using ZK.InterfaceServer;
using ZK.HardWareBLL;
using FastReport;
using System.Diagnostics;

namespace ZK.YHP_TransManage.UC
{
    /// <summary>
    /// 门卫室打印榜单
    /// </summary>
    public partial class PrintPoundList : Form
    {
        private string errorStr = string.Empty;
        /// <summary>
        /// 一页显示多少个数据
        /// </summary>
        int OnePageShowList = 10;
        /// <summary>
        /// 页数
        /// </summary>
        int count = 1;
        /// <summary>
        /// 室外读卡器
        /// </summary>
        //private MW_102N_CardReader mW_102N_CardReader;
        /// <summary>
        /// 运销车辆信息
        /// </summary>
        private Models.GetTruckYxInfoRceiveM yxYsTransportReturnDto;

        private WFAutoSizeHelper wFAutoSizeHelper = new WFAutoSizeHelper();

        Models.ScalesPrint scalesPrint = new Models.ScalesPrint();
        PrintPreviewDialog printPriview = new PrintPreviewDialog();
        List<Models.GetWeightBillsRceiveM1> getWeightBillsRceiveM1s;
        string PrintType;
        //private string nowCardNum = "";
        public PrintPoundList()
        {
            InitializeComponent();
            PrintType = AppConfigHelper.GetAppSettings("PrintType");
            yxYsTransportReturnDto = new Models.GetTruckYxInfoRceiveM();

            // Common.DelegateHelper.MW_102N_MessageReceivedEvent += MW_102N_MessageReceived;

            //window change event
            wFAutoSizeHelper.GetAllInitInfo(this.Controls[0], this);
            this.StartPosition = FormStartPosition.CenterScreen;
            //Common.DelegateHelper.SendWidthHeightEvent += SendWidthHeight;

            aspnetPager1.OnPageChanged += AspnetPager1_OnPageChanged;

            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
            dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
            dataGridView1.AutoGenerateColumns = true;
        }

        private void AspnetPager1_OnPageChanged(object sender, EventArgs e)
        {
            ShowData(out count);
        }

        private void ShowData(out int count, bool res = true)
        {
            int nums;
            dataGridView1.DataSource = null;
            string txtCurrentPage = aspnetPager1.Controls["panel1"].Controls["txtCurrentPage"].Text.Trim();
            if (string.IsNullOrWhiteSpace(txtCurrentPage)) txtCurrentPage = "1";
            nums = Convert.ToInt32(txtCurrentPage);

            Models.GetWeightBillsRceiveM getWeightBillsRceiveM = new Models.GetWeightBillsRceiveM();

            Models.GetWeightBillsSendM getWeightBillsSendM = new Models.GetWeightBillsSendM()
            {
                currentPage = nums,
                pageSize = this.OnePageShowList,
                cardNo = textBoxCardNum.Text.Trim(),
                truckNo = textBoxCarNum.Text.Trim(),
                // sendType = 2,
                reciveName = "安塘"
            };
            getWeightBillsRceiveM = AutoControlTransportApiServer.GetWeightBills(getWeightBillsSendM);
            if (getWeightBillsRceiveM != null && getWeightBillsRceiveM.data.Count > 0)
            {
                getWeightBillsRceiveM1s = getWeightBillsRceiveM.data;
                List<Models.PrintViewM> printViewMs = getWeightBillsRceiveM.data.Select(p => new Models.PrintViewM()
                {
                    cardNo = p.cardNo,
                    truckNo = p.truckNo,
                    sendType = p.sendType,
                    yxState = p.yxState,
                    driver = p.driver,
                    BillState = p.billState,
                    CPTime = p.platformLightWeightTime == null ? "" : p.platformLightWeightTime.Substring(5)
                }).ToList();
                dataGridView1.DataSource = printViewMs;
                count = getWeightBillsRceiveM.total;
            }
            else
            {
                count = 0;
            }

            ShowPage(count, res);

        }

        /// <summary>
        /// 分页控件
        /// </summary>
        /// <param name="list"></param>
        private void ShowPage(int num, bool res = true)
        {
            aspnetPager1.PageSize = OnePageShowList;//设置显示记录数
            if (res)
                aspnetPager1.DrawControl(num);
            else
                aspnetPager1.DrawControlFirst(num);
        }




        /// <summary>
        /// 窗口变化委托事件
        /// </summary>
        /// <param name="Width"></param>
        /// <param name="height"></param>
        private void SendWidthHeight(int Width, int height)
        {
            if (wFAutoSizeHelper.ControlsInfo.Count > 0)//如果字典中有数据，即窗体改变
            {
                wFAutoSizeHelper.ControlsChangeInit(Width, height);//表示pannel控件
                wFAutoSizeHelper.ControlsChange(this.Controls[0]);
            }
        }




        /// <summary>
        /// 判断是否打印预览，并关闭打印页面。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Document_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            System.Drawing.Printing.PrintDocument printDocument = sender as System.Drawing.Printing.PrintDocument;
            bool printRes = printDocument.PrintController.IsPreview;
            if (!printRes)
            {
                printPriview.Close();
            }
        }






        /// <summary>
        /// 打印预览
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonPrint_Click(object sender, EventArgs e)
        {
            //string cardNum = textBoxCardNum.Text.Trim();
            ////获取运单信息
            //var resGetInfoM = Com.WebApiService.GetTheLatest(cardNum);
            //if (!resGetInfoM.success)
            //{
            //    DialogNowMessageShow(resGetInfoM.msg);
            //    return;
            //}
            //if (resGetInfoM.data == null)
            //{
            //    DialogNowMessageShow("数据为空！");
            //    return;
            //}
            //yxYsTransportReturnDto = resGetInfoM.data;
            //打印预览
            scalesPrint.yxYsTransportReturnDto = yxYsTransportReturnDto;
            printPriview = new PrintPreviewDialog
            {
                Document = scalesPrint.printDocument(Models.ScalesPrint.ScalesType.one),
                WindowState = FormWindowState.Maximized,
            };
            printPriview.Document.BeginPrint += Document_BeginPrint;
            //printPriview.ShowDialog();//预览
            //printPriview.Document.Print();//直接打印
            // ClearText();
        }

        /// <summary>
        /// print event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //switch (PrintType)
            //{
            //    case "1":
            //        PrintATZB();
            //        break;
            //    case "2":
            //        PrintATQB();
            //        break;

            //    default:
            //        break;
            //}
            PrintATQB();
            button1_Click(null, null);

        }

        public void PrintATZB()
        {
            try
            {
                var nowRow = dataGridView1.CurrentRow;
                string cardNum = nowRow.Cells[3].Value.ToString();
                Models.GetWeightBillsRceiveM1 getWeightBillsRceiveM1 = getWeightBillsRceiveM1s.Where(p => p.cardNo == cardNum).FirstOrDefault();
                if (getWeightBillsRceiveM1 != null)
                {
                    Report report = new Report();
                    List<Models.PoundPrintM> poundPrintMs = new List<Models.PoundPrintM>();
                    decimal price = (Convert.ToDecimal(getWeightBillsRceiveM1.jz) * Convert.ToDecimal(getWeightBillsRceiveM1.salePrice));
                    string priceUpper = Number_String.ConvertToChinese(price);
                    Models.PoundPrintM poundPrintM = new Models.PoundPrintM()
                    {
                        Title = AppConfigHelper.GetAppSettings("PoundTitle"),
                        RoughWeightTime = getWeightBillsRceiveM1.mzTime,
                        TicketNumber = getWeightBillsRceiveM1.wbCode,
                        CoalName = getWeightBillsRceiveM1.shipperName,
                        Coal = getWeightBillsRceiveM1.coalName,
                        CarNumber = getWeightBillsRceiveM1.truckNo,
                        Carrier = getWeightBillsRceiveM1.carrierName,
                        Drawer = Common.IConfig.GetSetuserInfo.LoginAccount,

                        FootText = "FootText",
                    };
                    poundPrintMs.Add(poundPrintM);
                    report.Load(@"ATZBD.frx");
                    report.RegisterData(poundPrintMs, "m");
                    //预览打印
                    report.Show();
                    report.Dispose();

                    //静默打印
                    //report.PrintSettings.ShowDialog = false;//选择打印机页面是否显示
                    //report.PrintSettings.Printer = AppConfigHelper.GetAppSettings("printName");
                    //report.Print();
                    //report.Dispose();

                    var printWeightBillRes = AutoControlTransportApiServer.PrintWeightBill(getWeightBillsRceiveM1.wbid);
                    if (!printWeightBillRes.success)
                    {
                        Common.Log4.LogManage.WriteErr(printWeightBillRes.msg);
                        MessageBox.Show(printWeightBillRes.msg);
                    }
                }
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr(ex.ToString());
                MessageBox.Show(ex.Message);
            }
        }
        public void PrintATQB()
        {
            try
            {
                var nowRow = dataGridView1.CurrentRow;
                string cardNum = nowRow.Cells[3].Value.ToString();
                Models.GetWeightBillsRceiveM1 getWeightBillsRceiveM1 = getWeightBillsRceiveM1s.Where(p => p.cardNo == cardNum).FirstOrDefault();
                if (getWeightBillsRceiveM1 != null)
                {
                    var resSC = AutoControlTransportApiServer.AddWeightBill(new Models.AddWeightBillSendM()
                    {
                        cardNo = getWeightBillsRceiveM1.cardNo,
                        truckNo = getWeightBillsRceiveM1.truckNo
                    });
                    Common.Log4.LogManage.WriteInfo("生成榜单：" + Newtonsoft.Json.JsonConvert.SerializeObject(resSC));
                    if (!resSC.success)
                    {
                        Common.Log4.LogManage.WriteErr(resSC.msg);
                        MessageBox.Show(resSC.msg);
                    }
                    Report report = new Report();
                    List<Models.PoundPrintM> poundPrintMs = new List<Models.PoundPrintM>();
                    string DeductionTon = Com.BDTools.GetDeductionTon(getWeightBillsRceiveM1.jz, getWeightBillsRceiveM1.platformJz);
                    string DeductionMoney = Com.BDTools.GetDeductionMoney(DeductionTon, getWeightBillsRceiveM1.salePrice);
                    string Freight = Com.BDTools.GetFreight(getWeightBillsRceiveM1.platformJz, getWeightBillsRceiveM1.transportPrice, DeductionMoney);
                    Models.PoundPrintM poundPrintM = new Models.PoundPrintM()
                    {
                        Title = AppConfigHelper.GetAppSettings("PoundTitle"),
                        PlatformHeavyPoundTime = getWeightBillsRceiveM1.platformLightWeightTime,
                        TicketNumber = getWeightBillsRceiveM1.wbCode,
                        CoalName = getWeightBillsRceiveM1.shipperName,
                        Coal = getWeightBillsRceiveM1.coalName,
                        CarNumber = getWeightBillsRceiveM1.truckNo,
                        Carrier = getWeightBillsRceiveM1.carrierName,
                        Drawer = Common.IConfig.GetSetuserInfo.LoginAccount,

                        FootText = "FootText",
                        OreOutput = getWeightBillsRceiveM1.jz,
                        PlatformNetWeight = getWeightBillsRceiveM1.platformJz,
                        DeductionTon = DeductionTon,
                        DeductionMoney = DeductionMoney,
                        TransportPrice = getWeightBillsRceiveM1.transportPrice,
                        Freight = Freight,
                    };
                    poundPrintMs.Add(poundPrintM);
                    report.Load(@"ATQBD.frx");
                    report.RegisterData(poundPrintMs, "m");
                    //预览打印
                    //report.Show();
                    //report.Dispose();

                    //静默打印
                    report.PrintSettings.ShowDialog = false;//选择打印机页面是否显示
                    report.PrintSettings.Printer = AppConfigHelper.GetAppSettings("printName");
                    report.Print();
                    report.Dispose();

                    var printWeightBillRes = AutoControlTransportApiServer.PrintWeightBill(getWeightBillsRceiveM1.wbid);
                    if (!printWeightBillRes.success)
                    {
                        Common.Log4.LogManage.WriteErr(printWeightBillRes.msg);
                        MessageBox.Show(printWeightBillRes.msg);
                    }
                }
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr(ex.ToString());
                MessageBox.Show(ex.Message);
            }
        }

        private void PrintPoundList_SizeChanged(object sender, EventArgs e)
        {
            if (wFAutoSizeHelper.ControlsInfo.Count > 0)//如果字典中有数据，即窗体改变
            {
                wFAutoSizeHelper.ControlsChangeInit(this.Controls[0]);//表示pannel控件
                wFAutoSizeHelper.ControlsChange(this.Controls[0]);
                // Common.DelegateHelper.SendWidthHeightEvent?.Invoke(this.Controls[0].Width, this.Controls[0].Height);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            aspnetPager1.Controls["panel1"].Controls["txtCurrentPage"].Text = "1";
            count = 1;
            ShowData(out count, false);
        }

        private void PrintPoundList_FormClosing(object sender, FormClosingEventArgs e)
        {
            DelegateHelper.WeightToListEvent -= WeightToListEvent1;
        }
        private void WeightToListEvent1(string cardNum, string carNum)
        {
            //this?.Invoke(new Action(() =>
            //{
            //    textBoxCardNum.Text = cardNum;
            //    textBoxCarNum.Text = carNum;
            //    button1_Click(null, null);
            //}));

        }
    }


}
